# -*- encoding: utf-8 -*-
# ePhorte parser
# http://www.harstad.kommune.no/ephorteweb/shared/aspx/default/Search.aspx?Profile=-20,0&Theme=Public,Default&BPS_ID=-500&Run=1&JP_JDATO=03.10.2007
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging, re
from datetime import datetime
from time import strptime
from cgi import parse_qs
import BeautifulSoup
import jeje.parser

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        #jeje.parser.ejeje_parser.__init__(self, suppe, postjournal_samling)
        logging.info('starter ePhorte-parser')
        #dato = suppe.h1.string[len('Dagens postjournal '):]
        #logging.debug('fant dato %s', dato)
        #self.sett_info(dato)
        logging.debug('finner tittelposter i suppa')
        _tittelposter = suppe.findAll(tagparser)#lambda tag: tag.name=='tr' and tag.attrs['class'] in ('GI', 'TLI'))
        logging.debug('fant %d titler', len(_tittelposter))
        for i, tp in enumerate(_tittelposter):
             #<a title="Dokumenttype"
            #<a title="Innhold"
            #<a title="Avsender/Mottaker"
            #<a title="Tilgangskode"
            #<a title="Dokumentdato"
            #<td style="width:21px;white-space:nowrap;">
                        #<input id="SearchPanel1_view602JournPost_RadGrid1_ctl01_ctl08_CheckBox1" type="checkbox" name="SearchP
            #id1$ctl01$ctl08$CheckBox1" />
                #</td><td align="center" style="white-space:nowrap;">
                        #<span>I</span>
                #</td><td style="white-space:nowrap;">
                        #<a href="/risor/shared/aspx/default/details.aspx?f=ViewJP PUB&amp;JP_ID=22385" target="rbottom"><span>
            #bilitering av sla...</span></a>
                #</td><td style="white-space:nowrap;">
                        #<span>Slagenheten Rehab. G...</span>
                #</td><td align="left" style="white-space:nowrap;">
                        #<span></span>
                #</td><td style="white-space:nowrap;">
                        #<span>23.07.2007</span>
                #</td>

            try: # some implementations have six columns, some five
                __junk, _type, _tittel, _adressat, _grad, _dokumentdato = [b for b in tp.findAll('td')]
            except ValueError:
                _type, _tittel, _adressat, _grad, _dokumentdato = [b for b in tp.findAll('td')]

            try:
                tittel = _tittel.span['title']
            except KeyError:
                tittel = self.trekk_ut_streng(_tittel)#.span.string
            logging.debug('arbeider med post #%d: %s', i+1, tittel)

            post = self.legg_til_post()
            post.sett_tittel(unicode(tittel))
            ##logging.debug('arkivsaksnr: %s, refnr: %s', _arkivsaksnr, _refnr)
            #post.sett_arkivsaksnr(self.trekk_sammen_streng(_arkivsaksnr))
            try:
                post.sett_adressat(unicode(_adressat.span['title']))
            except KeyError:
                post.sett_adressat(self.trekk_ut_streng(_adressat))#.span.string))
            #person = post.sett_saksbehandler(str(_saksbehandler[0].string))
            #person.sett_uri(_saksbehandler[0]['href'])
            try:
                post.sett_dokumentdato(datetime(*strptime(_dokumentdato.span.span.string.strip(), '%d.%m.%Y')[0:6]))
            except AttributeError:
                post.sett_dokumentdato(datetime(*strptime(_dokumentdato.span.string.strip(), '%d.%m.%Y')[0:6]))
            
            gradering = self.trekk_ut_streng(_grad)
            gradkart = { 'P': u'Personalsaker',
                         'S': u'Skatt- og innfordring',
                         'U': u'Unntatt offentlighet',
                         }
            if gradering in gradkart.keys(): # Unntatt offentlighet
                post.sett_offentlig(False)
                post.sett_lovreferanse(gradkart[gradering])
                
            post.sett_dok_uri(self.absoluttifiser(unicode(_tittel.a['href']), uri))
            post.sett_refnr(unicode(parse_qs(post.dok_uri.split('?')[1])['JP_ID'][0]))
            post.sett_retning(self.trekk_ut_streng(_type))
            post.kontroller_felter()
                
        return self.journalposter

def tagparser(tag):
    try:
        return tag.name=='tr' and tag['class'] in ('GI', 'TLI')
    except:
        return False
        
